package com.example.backend.controller;

import com.example.backend.entity.StorageRecord;
import com.example.backend.service.StorageFeeService;
import com.example.backend.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/storage")
public class StorageFeeController {

    @Autowired
    private StorageFeeService storageFeeService;

    @PostMapping("/record")
    public ApiResponse<Object> addRecord(@RequestBody StorageRecord record) {
        StorageRecord savedRecord = storageFeeService.saveRecord(record);
        Map<String, Object> response = new HashMap<>();
        response.put("id", savedRecord.getId());
        response.put("storageFee", savedRecord.getStorageFee());
        response.put("remainingWeight", savedRecord.getRemainingWeight());
        return ApiResponse.success(response);
    }

    @GetMapping("/records")
    public ApiResponse<List<StorageRecord>> getAllRecords() {
        return ApiResponse.success(storageFeeService.getAllRecords());
    }

    @GetMapping("/records/range")
    public ApiResponse<List<StorageRecord>> getRecordsByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date end) {
        return ApiResponse.success(storageFeeService.getRecordsByDateRange(start, end));
    }

    @GetMapping("/summary")
    public ApiResponse<Object> getSummary() {
        BigDecimal totalEntry = storageFeeService.calculateTotalEntryWeight();
        BigDecimal totalOut = storageFeeService.calculateTotalOutWeight();
        BigDecimal totalFee = storageFeeService.calculateTotalFee();

        Map<String, Object> summary = new HashMap<>();
        summary.put("totalEntryWeight", totalEntry);
        summary.put("totalOutWeight", totalOut);
        summary.put("totalFee", totalFee);

        return ApiResponse.success(summary);
    }
}